
package com.compuvest.web;

// <editor-fold defaultstate="collapsed" desc="import">
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
// </editor-fold>

public final class SessionEvent implements HttpSessionListener {

    public static final Logger log = LoggerFactory.getLogger(SessionEvent.class);

// <editor-fold defaultstate="collapsed" desc="sessionCreated()">

    @Override
    public void sessionCreated(HttpSessionEvent event) {

        HttpSession session = event.getSession();
//	if(session == null) return;
        try {
            // get basket from DB
//	    MySQL sb = (MySQL)session.getServletContext().getAttribute("sb");
//	    Basket basket = sb.getBasket(session.getId());

            session.setAttribute("basket",  new Basket());

	    // add client
//	    Map<String,Clickstream> clientsList = (Map<String,Clickstream>)session.getServletContext().getAttribute("context.clientList");
//	    clientsList.put(session.getId(), basket.getClickstream());
        }
	catch(Exception ex) {
            log.error("sessionCreated: " + ex);
        }
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="sessionDestroyed()">

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {

	HttpSession session = event.getSession();
//	if(session == null) return;
	try {
	    // delete client from list
//	    Map<String,Clickstream> clientsList = (Map<String,Clickstream>)session.getServletContext().getAttribute("context.clientList");
//	    clientsList.remove(session.getId());

	    MySQL sb = (MySQL)session.getServletContext().getAttribute("sb");
	    Basket basket = (Basket)session.getAttribute("basket");
	    // save basket
	    if(basket.size() != 0) {
		sb.setBasket(basket, session.getId());
            }

	    Customer cust = basket.getCustomer();
	    if(cust != null && cust.getCustomerID() == 0) {

	        // send email to lost customer
	        Mail mail = (Mail)session.getServletContext().getAttribute("mail");
	        mail.sendEmailToLostCustomer(cust.getEmail());

	        // write down for statistic
                sb.newCustomer(cust, basket.getClickstream().getIPAddress());

	    }

	    // delete
	    session.removeAttribute("basket");
	    session.removeAttribute("backItemsPage");
	}
	catch(Exception ex) {
            log.error("sessionDestroyed: " + ex);
        }
    }
// </editor-fold>

}
